package com.mask.common.mybatis.config;


import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    /**
     * 动态数据源配置
     */
//    @Bean
//    @ConfigurationProperties(prefix = "spring.datasource.dynamic")
//    public DynamicDataSourceProperties dynamicDataSourceProperties() {
//        return new DynamicDataSourceProperties();
//    }

    /**
     * 配置动态数据源
     */
//    @Bean
//    public DynamicDataSource dynamicDataSource(DynamicDataSourceProperties properties) {
//        DynamicDataSource dynamicDataSource = new DynamicDataSource();
//
//        // 配置默认数据源
//        DataSource defaultDataSource = createDataSource(properties.getPrimary());
//        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
//
//        // 配置多数据源
//        Map<Object, Object> targetDataSources = new HashMap<>();
//        properties.getDatasource().forEach((k, v) -> {
//            DataSource ds = createDataSource(v);
//            targetDataSources.put(k, ds);
//        });
//        dynamicDataSource.setTargetDataSources(targetDataSources);
//
//        return dynamicDataSource;
//    }

    /**
     * 创建数据源
     */
    private DataSource createDataSource(DataSourceProperty property) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(property.getDriverClassName());
        dataSource.setJdbcUrl(property.getUrl());
        dataSource.setUsername(property.getUsername());
        dataSource.setPassword(property.getPassword());
        return dataSource;
    }
}